package com.imooc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.InputStream;

@RestController
@RequestMapping("upload")
public class UploadController {

    @Value("${web.upload.path}")
    private String uploadPath;

    @PostMapping("image")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        FileOutputStream fs = new FileOutputStream(uploadPath+file.getOriginalFilename());
        while (true){
            int readData = inputStream.read();
            if (readData == -1){
                break;
            }
            fs.write(readData);
        }
        fs.close();
        System.out.println(file.getOriginalFilename());
        return ResponseEntity.ok("/sell/file/"+file.getOriginalFilename());
    }
}